<template>
  <component :is="useDrawer ? 'el-drawer' : 'el-dialog'" :title="dialogTitle" :visible.sync="dialogVisible"
    :size="useDrawer ? '75%' : undefined" :width="useDrawer ? undefined : '75%'" @close="resetForm" destroy-on-close>

    <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px" style="margin-right: 12px; margin-bottom: 120px;">

      <div class="flex-x">
        <el-form-item label="活动" prop="collId" class="flex-1">
          <coll-select v-model="formData.collId" class="w-full"/>
        </el-form-item>

        <el-form-item label="题目类型" prop="questionType" class="flex-1">
          <el-select v-model="formData.questionType" placeholder="请选择题目类型">
            <el-option label="单选题" :value="1"></el-option>
            <el-option label="多选题" :value="2"></el-option>
            <el-option label="填空题" :value="3"></el-option>
            <el-option label="简答题" :value="4"></el-option>
          </el-select>
        </el-form-item>
      </div>

      <div class="flex-x">
        <el-form-item label="排序" prop="sortOrder" class="flex-1">
          <el-input-number v-model="formData.sortOrder" :min="0" />
        </el-form-item>

        <el-form-item label="分值" prop="score" class="flex-1">
          <el-input-number v-model="formData.score" :min="0" />
        </el-form-item>
      </div>

      <el-form-item label="题目内容" prop="title">
        <Editor :value.sync="formData.title" />
      </el-form-item>


    </el-form>

    <div :slot="useDrawer ? 'default' : 'footer'" :class="['flex-x', 'dialog-footer', { 'drawer-footer': useDrawer }]">
      <div class="navigation-buttons" v-if="formData.id">
        <el-button size="small" icon="el-icon-arrow-left" @click="navigateQuestion('prev')">上一题</el-button>
        <el-button size="small" icon="el-icon-arrow-right" @click="navigateQuestion('next')">下一题</el-button>
      </div>
      <div class="flex-1"></div>
      <div class="action-buttons">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </div>
  </component>
</template>

<script>
import api from '@/common/api';

import Editor from '@/components/admin/Editor';
import CollSelect from "@/components/admin/ItechCollSelect.vue";

export default {
  name: 'EditSampleDialog',
  props: {
    useDrawer: {
      type: Boolean,
      default: false
    }
  },

  components: {
    CollSelect,
    Editor
  },

  data() {
    return {
      loading: false,
      dialogVisible: false,
      lastUsedScore: Number(localStorage.getItem('lastQuestionScore') || '0'),

      // 不同题型的默认模板
      templates: {
        1: `这是一道单选题，请开始输入题干内容吧。
1. 请勿编辑以"==="开头的内容
2. 请勿编辑选项前的字母编码和空格
3. 在最后一行输入正确答案编号，例如：A

===> options
A 选项A的内容
B 选项B的内容
C 选项C的内容
D 选项D的内容
===> answer
A
`,
        2: `这是一道多选题，请开始输入题干内容吧。
1. 请勿编辑以"==="开头的内容
2. 请勿编辑选项前的字母编码和空格
3. 在最后一行输入正确答案编号，可以多选，例如：ABC

===> options
A 选项A的内容
B 选项B的内容
C 选项C的内容
D 选项D的内容
===> answer
AB
`,
        3: `小明今年8岁，爸爸的年龄是小明的4倍，爸爸今年______岁。

===> answer
32
`,
        4: `请简述你对人工智能的理解。`
      },

      formData: {
        title: '',
        sortOrder: 0,
        score: 2,
        questionType: 1
      },
      rules: {
        questionType: [
          { required: true, message: '请选择题目类型', trigger: 'change' },
        ],
        title: [
          { required: true, message: '请输入题目内容', trigger: 'blur' },
        ],
        sortOrder: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ],
        score: [
          { required: true, message: '请输入分值', trigger: 'blur' }
        ]
      }
    }
  },

  computed: {
    dialogTitle() {
      return this.formData.id ? '编辑题目' : '添加题目'
    }
  },

  watch: {
    // 监听题目类型变化，自动填充默认模板
    'formData.questionType'(newType, oldType) {
      // 只在新增题目时自动填充（有id的是编辑题目，不自动填充）
      if (!this.formData.id && newType && oldType !== undefined) {
        this.formData.title = this.templates[newType] || ''
      }
    }
  },

  methods: {
    async open(data) {
      this.formData = Object.assign({}, this.formData, data)

      if (!this.formData.id) {
        this.formData.questionType = 1    // 默认单选题
        this.formData.score = this.lastUsedScore || 0   // 上一题的分值
        this.formData.title = this.templates[this.formData.questionType] || this.templates[1]
      } else {
        const { data } = await api.admin_getItechCollQuestionDetailEdit({
          id: this.formData.id
        })
        this.formData = data.data
      }

      this.dialogVisible = true
    },

    resetForm() {
      this.$refs.formRef?.resetFields()
      this.formData = {
        title: '',
        content: '',
        questionType: 1,
        sortOrder: 0,
      }
    },

    submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return

        try {
          this.loading = true
          if (!this.formData.id) {
            this.lastUsedScore = this.formData.score
            localStorage.setItem('lastQuestionScore', this.formData.score)
          }
          const { data } = await api.admin_saveItechCollQuestion(this.formData)
          this.$message.success('保存成功')          

          this.$emit('success', data.data)
        } finally {
          this.loading = false
        }
      })
    },

    async navigateQuestion(direction) {
      try {
        this.loading = true

        let sortOrder = this.formData.sortOrder || 0
        if (direction === 'prev') {
          sortOrder -= 1
        } else {
          sortOrder += 1
        }

        // 查询上一题或下一题
        const { data } = await api.admin_getItechCollQuestionDetailEdit({
          collId: this.formData.collId,
          sortOrder: sortOrder
        })

        if (data.data) {
          // 加载查询到的题目
          this.formData = data.data
        } else {
          this.$message.info(direction === 'prev' ? '已经是第一题' : '已经是最后一题')
        }
      } catch (error) {
        console.error(error)
        this.$message.error('获取题目失败')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.navigation-buttons {
  display: flex;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 1px solid #e4e7ed;
  z-index: 4000;
}
</style>
